#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: mongo_for_api.py 
@version:
@time: 2022/03/01 
"""
import pymongo
from pymongo import MongoClient


class MongoForApi:

    def __init__(self, info):
        mongoUrl = f'mongodb://{info["host"]}:{info["port"]}/{info["db"]}'
        self.client: MongoClient = pymongo.MongoClient(mongoUrl)
        self.db = info["db"]

    def find(self, table, query=None):
        if query is None:
            query = {}
        return self.client[self.db][table].find(query)

    def query(self, table, query=None):
        if query is None:
            query = {}
        return list(self.client[self.db][table].find(query))

    def show_dbs(self):
        return list(self.client.list_database_names())

    def show_collections(self):
        return list(self.client[self.db].list_collection_names())

    def update(self, table, query, document):
        return self.client[self.db][table].update_one(query, document)

    def update_many(self, table, query, document):
        return self.client[self.db][table].update_many(query, document)

    def insert_one(self, table, document):
        return self.client[self.db][table].insert_one(document)

    def insert_many(self, table, document):
        return self.client[self.db][table].insert_many(document)

    def delete_one(self, table, document):
        return self.client[self.db][table].delete_one(document)

    def delete_many(self, table, document):
        return self.client[self.db][table].delete_many(document)

    def drop_collection(self, table):
        return self.client[self.db].drop_collection(table)

    def close(self):
        self.client.close()
